<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button type="primary" icon="el-icon-plus" @click="handleCreate">
        添加分类
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="categoryList"
      element-loading-text="加载中..."
      border
      fit
      highlight-current-row
      row-key="id"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="分类名称" min-width="200">
        <template slot-scope="{row}">
          <span>{{ row.categoryName }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="图标" width="100" align="center">
        <template slot-scope="{row}">
          <el-image 
            v-if="row.icon" 
            :src="row.icon" 
            style="width: 40px; height: 40px;"
            fit="cover"
          ></el-image>
          <span v-else>-</span>
        </template>
      </el-table-column> -->
      <el-table-column label="排序" width="100" align="center">
        <template slot-scope="{row}">
          <span>{{ row.orderNum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="180" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status === 0" size="mini" type="success" @click="handleModifyStatus(row, 1)">
            启用
          </el-button>
          <el-button v-else size="mini" type="info" @click="handleModifyStatus(row, 0)">
            禁用
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分类表单对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="temp.categoryName" placeholder="请输入分类名称" />
        </el-form-item>
        <!-- <el-form-item label="分类图标">
          <image-upload v-model="temp.icon"/>
        </el-form-item> -->
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="temp.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="temp.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="temp.description" type="textarea" :rows="2" placeholder="请输入分类描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogDeleteVisible"
      width="30%">
      <span>确定要删除该分类吗？删除后不可恢复，且会同时删除其下所有子分类。</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogDeleteVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDelete">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listCategory, getCategory, addCategory, updateCategory, delCategory, changeStatus } from '@/api/shop/category'

export default {
  name: 'CategoryManagement',
  data() {
    return {
      categoryList: [], // 分类列表
      categoryOptions: [], // 分类选择器选项
      listLoading: true,
      dialogFormVisible: false,
      dialogDeleteVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑分类',
        create: '添加分类'
      },
      deleteId: null, // 要删除的分类ID
      temp: {
        id: undefined,
        categoryName: '',
        icon: '',
        orderNum: 0,
        status: 1,
        description: ''
      },
      rules: {
        categoryName: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }],
        sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取分类列表
    getList() {
      this.listLoading = true
      const query = {
        pageNum: 1,
        pageSize: 100
      }
    //   有没有shopId
      // if (this.shopId) {
      //   query.shopId = this.shopId
      // }
      // 调用接口获取分类列表
      listCategory(query).then(response => {
        this.categoryList = this.handleTree(response.data, "categoryId", "parentId")
        this.generateCategoryOptions()
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    // 生成分类选择器的选项
    generateCategoryOptions() {
      // 深拷贝分类列表，避免修改原数据
      const options = JSON.parse(JSON.stringify(this.categoryList))
      // 添加分类选项
      this.categoryOptions = options
    },
    // 重置表单
    resetTemp() {
      this.temp = {
        id: undefined,
        categoryName: '',
        icon: '',
        sort: 0,
        status: 1,
        description: ''
      }
    },
    // 处理创建分类
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 创建数据
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          addCategory(tempData).then(response => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建分类成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    // 处理更新分类
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // 复制对象，避免修改原数据
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 更新数据
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateCategory(tempData).then(response => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新分类成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    // 处理删除分类
    handleDelete(row) {
      this.deleteId = row.id
      this.dialogDeleteVisible = true
    },
    // 确认删除
    confirmDelete() {
      if (this.deleteId) {
        delCategory(this.deleteId).then(response => {
          this.dialogDeleteVisible = false
          this.$notify({
            title: '成功',
            message: '删除分类成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      }
    },
    // 修改分类状态
    handleModifyStatus(row, status) {
      const data = { id: row.id, status: status }
      changeStatus(data).then(response => {
        this.$message({
          message: '状态更新成功',
          type: 'success'
        })
        row.status = status
      })
    },
    // 图标上传成功处理
    handleIconSuccess(res, file) {
      // 假设上传接口返回的数据中包含图片URL
      this.temp.icon = res.data.url
    },
    // 图标上传前的验证
    beforeIconUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图标只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图标大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 处理树形数据转换
    handleTree(data, id, parentId, children) {
      let config = {
        id: id || 'id',
        parentId: parentId || 'parentId',
        childrenList: children || 'children'
      };

      var childrenListMap = {};
      var nodeIds = {};
      var tree = [];

      for (let d of data) {
        let parentId = d[config.parentId];
        if (childrenListMap[parentId] == null) {
          childrenListMap[parentId] = [];
        }
        nodeIds[d[config.id]] = d;
        childrenListMap[parentId].push(d);
      }

      for (let d of data) {
        let parentId = d[config.parentId];
        if (nodeIds[parentId] == null) {
          tree.push(d);
        }
      }

      for (let t of tree) {
        adaptToChildrenList(t);
      }

      function adaptToChildrenList(o) {
        if (childrenListMap[o[config.id]] !== null) {
          o[config.childrenList] = childrenListMap[o[config.id]];
        }
        if (o[config.childrenList]) {
          for (let c of o[config.childrenList]) {
            adaptToChildrenList(c);
          }
        }
      }
      return tree;
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>